package sys

import (
	"errors"
	"faker/project-public/global"
	"faker/project-public/model/sys"
	"faker/project-public/request"
	"gorm.io/gorm"
	"sort"
)

type RuleService struct {
}

func (ruleService *RuleService) CreateRule(addRule sys.SysRule) (err error) {
	if !errors.Is(global.FAKER_DB.Where("route = ?", addRule.Route).First(&addRule).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在相同的route")
	}
	err = global.FAKER_DB.Create(&addRule).Error
	return err
}

// GetRuleList 获取用户列表
func (ruleService *RuleService) GetRuleList(info request.PageInfo) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.FAKER_DB.Model(&sys.SysRule{})
	var ruleList []sys.SysRule
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Find(&ruleList).Error
	return ruleList, total, err
}
func (ruleService *RuleService) GetMenuTree(info request.PageInfo) (menuTree []*sys.SysRule, total int64, err error) {
	// 从数据库中获取所有的菜单数据
	var ruleAllData []*sys.SysRule
	err = global.FAKER_DB.Model(&sys.SysRule{}).Order("id asc").Find(&ruleAllData).Error
	if err != nil {
		return nil, 0, err
	}

	// 构建菜单节点映射
	menuMap := make(map[int64]*sys.SysRule)
	for _, menu := range ruleAllData {
		menuMap[int64(menu.ID)] = &sys.SysRule{
			ID:         menu.ID,
			Route:      menu.Route,
			Icon:       menu.Icon,
			Rule:       menu.Rule,
			Title:      menu.Title,
			IsMenu:     menu.IsMenu,
			SortId:     menu.SortId,
			Status:     menu.Status,
			Depth:      menu.Depth,
			CreateTime: menu.CreateTime,
			Children:   []*sys.SysRule{}, // 初始化Children为一个空的指针切片
		}
	}

	// 从数据库中获取当前页的菜单数据

	db := global.FAKER_DB.Model(&sys.SysRule{})
	// 获取总记录数
	err = db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}
	// 构建菜单树
	for _, menu := range ruleAllData {
		if menu.Pid == 0 {
			menuTree = append(menuTree, menuMap[int64(menu.ID)])
		} else {
			parentNode, ok := menuMap[int64(menu.Pid)]
			if !ok {
				continue // 如果找不到父节点，则跳过当前菜单
			}
			ruleData := parentNode.Children
			updatedNode := menuMap[int64(menu.ID)]
			parentNode.Children = append(ruleData, updatedNode)
		}
	}

	return menuTree, total, nil
}

// GetRuleInfo 获取菜单信息
func (ruleService *RuleService) GetRuleInfo(id int) (ruleInfo sys.SysRule, err error) {
	err = global.FAKER_DB.Where("id = ?", id).First(&ruleInfo).Error
	return ruleInfo, err
}

// SetRule 设置菜单信息
func (ruleService *RuleService) SetRule(info sys.SysRule) (err error) {
	var setRule sys.SysRule
	db := global.FAKER_DB.Model(&setRule)
	err = CheckDuplicateRuleRoute(info)
	if err != nil {
		// 处理角色名重复的情况
		return errors.New("存在重复route，请修改route")
	}
	updateData := map[string]interface{}{"route": info.Route, "title": info.Title, "icon": info.Icon, "rule": info.Rule,
		"sort_id": info.SortId}
	err = db.Where("id = ?", info.ID).Updates(updateData).Error
	if err != nil {
		return errors.New("更新路径失败")
	}
	return err
}

// CheckDuplicateRuleRoute 检测数据重复
func CheckDuplicateRuleRoute(info sys.SysRule) error {
	var setRule sys.SysRule
	db := global.FAKER_DB.Model(&setRule)
	err := db.Where("id != ?", info.ID).Where("route = ?", info.Route).First(&setRule).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		// 查询过程中发生其他错误
		return err
	}
	if setRule.ID != 0 {
		// 角色名重复
		return errors.New("路径名重复")
	}
	return nil
}

// DeleteRule 删除菜单
func (ruleService *RuleService) DeleteRule(id int) (err error) {
	var ruleInfo sys.SysRule
	err = global.FAKER_DB.Where("id = ?", id).First(&ruleInfo).Error
	if err != nil {
		return errors.New("无此路由")
	}
	err = global.FAKER_DB.Where("id = ?", id).Delete(&ruleInfo).Error
	return err
}

func (ruleService *RuleService) GetUserMenuTree(rid int) (menuTree []*sys.SysRule, err error) {
	// 从数据库中获取所有的菜单数据
	var roles sys.SysRole
	err = global.FAKER_DB.Where("role_id = ?", rid).Preload("Rules").First(&roles).Error
	if err != nil {
		return
	}

	// 构建菜单节点映射
	menuMap := make(map[int64]*sys.SysRule)
	for _, menu := range roles.Rules {
		menuMap[int64(menu.ID)] = &sys.SysRule{
			ID:         menu.ID,
			Route:      menu.Route,
			Icon:       menu.Icon,
			Rule:       menu.Rule,
			Title:      menu.Title,
			IsMenu:     menu.IsMenu,
			SortId:     menu.SortId,
			Status:     menu.Status,
			Depth:      menu.Depth,
			CreateTime: menu.CreateTime,
			Children:   []*sys.SysRule{}, // 初始化Children为一个空的指针切片
		}
	}

	// 构建菜单树
	for _, menu := range roles.Rules {
		if menu.Pid == 0 {
			menuTree = append(menuTree, menuMap[int64(menu.ID)])
		} else {
			parentNode, ok := menuMap[int64(menu.Pid)]
			if !ok {
				continue // 如果找不到父节点，则跳过当前菜单
			}
			ruleData := parentNode.Children
			updatedNode := menuMap[int64(menu.ID)]
			parentNode.Children = append(ruleData, updatedNode)
		}
	}
	//根据sort_id进行升序
	sort.Slice(menuTree, func(i, j int) bool {
		return menuTree[i].SortId < menuTree[j].SortId
	})
	return menuTree, nil
}

func (ruleService *RuleService) GetAllRules() (list interface{}, err error) {
	// 从数据库中获取所有的菜单数据
	var ruleAllData []*sys.SysRule
	err = global.FAKER_DB.Model(&sys.SysRule{}).Order("id asc").Find(&ruleAllData).Error
	if err != nil {
		return
	}
	return ruleAllData, nil
}
